'''
开启脚本录制cmd命令： playwright codegen -o 存放生成代码路径  打开的网址
保存cookie cmd命令：playwright codegen --save-storage=cookie.json https://cc-test.b2bwings.com/villageMember
使用已保存的Cookie: playwright codegen --load-storage=cookie.json https://cc-test.b2bwings.com/villageMember
# 加载保存的 Cookie
browser = p.chromium.launch(headless=False)
context = browser.new_context(storage_state="D:\Desktop\python\cookie.json")
'''
import time
import asyncio
import keyboard
import unittest
from playwright.sync_api import sync_playwright
from playwright.async_api import async_playwright

#同步用例
class Test(unittest.TestCase):
    browse = 'msedge'
    browser_port = None

    @classmethod
    def setUpClass(self):
        self.playwright = sync_playwright().start()
        if self.browser_port is None:
            self.browser = self.playwright.chromium.launch(headless=False, channel=self.browse, args=['--start-maximized'])
            self.context = self.browser.new_context(no_viewport=True)
            self.page = self.context.new_page()
            # keyboard.press_and_release('f11')#全屏展示
        else:
            browser = self.playwright.chromium.connect_over_cdp(f"http://127.0.0.1:{self.browser_port}")
            self.page = browser.contexts[0].pages[0]  # 获取第一个页面
        self.page.set_default_timeout(60000)# 设置全局默认超时,不设置Playwright默认30秒

    @classmethod
    def tearDownClass(self):
        self.browser.close()
        self.playwright.stop()

    def test_01(self):
        self.page.goto('https://cqjy.gdagri.gov.cn/trade-list/auction')
        self.page.click("text=续约交易")
        print(self.page.locator('.el-image__inner').nth(0).get_attribute('src'))

    def test_02(self):
        '''地址不为空'''
        text = self.page.locator('.trade-page-goods_list_addr').nth(0).text_content()
        self.assertIsNotNone(text)



#异步用例
async def playwright_example():
    browser_port = None
    async with async_playwright() as p:
        if browser_port is None:
            # 启动浏览器（默认使用Chromium）
            browser = await p.chromium.launch(headless=False, channel='msedge', args=['--start-maximized'])
            page = await browser.new_page()
        else:
            browser = self.playwright.chromium.connect_over_cdp(f"http://127.0.0.1:{self.browser_port}")
            page = browser.contexts[0].pages[0]  # 获取第一个页面
        # 导航到百度
        await page.goto("https://www.baidu.com")
        # 在搜索框输入"Playwright"
        await page.fill('input[name="wd"]', "Playwright")
        # 点击搜索按钮
        await page.click('input[type="submit"]')
# 运行异步函数
asyncio.run(playwright_example())



